<?php
$db_server = $argv[1];
$db_user = $argv[2];
$db_pwd = $argv[3];
if ($db_pwd == 'no-pwd') $db_pwd = '';
$db_name = $argv[4];
$file_name = $argv[5];
$file_inc = $argv[6];
if (empty($file_name)) {
   $file_name = 'dbimage.txt';
}
if (empty($file_inc)) {
   $file_inc = 'aStructMB.const.php';
}

echo "$db_server, $db_user, $db_pwd, $db_name, $file_name.\n";
if (!$fout = fopen($file_name, 'w')) {
   die("impossibile creare il file $file_name\n");
}
if (!$finc = fopen($file_inc, 'w')) {
   die("impossibile creare il file $file_inc\n");
}
$sinc = "<?\r\n\$aStrutMB = array();\r\n";
fputs($finc, $sinc);

if (!$conn = mysql_connect($db_server, $db_user, $db_pwd)) {
   die(mysql_error());
}
if (!$db = mysql_select_db($db_name)) {
   die(mysql_error());
}
$sql = "SHOW TABLES";
if (!$qryt = mysql_query($sql)) {
   die($sql . ' - ' . mysql_error());
} 
while ($rect = mysql_fetch_array($qryt)) {
   $adb = array();
   $tab = $rect[0];
   // definizione colonne
   $sql = "SHOW FULL COLUMNS FROM $tab";
   if (!$qryc = mysql_query($sql)) {
      die($sql . ' - ' . mysql_error());
   }
   $sout = "$tab";
   while ($recc = mysql_fetch_assoc($qryc)) {
      $type = $recc['Type'];
      if (substr($type,0,6)=='varbin') {
         $type = 'varchar'.substr($type,6).' binary';
      } elseif (isset($recc['Collation']) and $recc['Collation'] == 'utf8_bin') {
				if (substr($type,-7) != ' binary') {
					$type .= ' binary';
				}
      }
		$nullable = ($recc['Null'] == 'YES')?'YES':'';	
      $sout = "$tab\tcol\t";
      $sout .= $recc['Field'] . "\t";
      $sout .= $type . "\t";
      $sout .= $nullable . "\t";
      $sout .= $recc['Default'] . "\t";
      $sout .= $recc['Extra'];
      $sout .= "\r\n";
      fputs($fout, $sout);
   }
   // definizione indici
   $sql = "SHOW INDEX FROM $tab";
   if (!$qryc = mysql_query($sql)) {
      die($sql . ' - ' . mysql_error());
   }
   while ($recc = mysql_fetch_assoc($qryc)) {
      $sout = "$tab\tind\t";
      $sout .= $recc['Key_name'] . "\t";
      $sout .= $recc['Seq_in_index'] . "\t";
      $sout .= $recc['Column_name'] . "\t";
      if ($recc['Index_type'] == 'FULLTEXT') {
         $sout .= $recc['Index_type'];
      } else {
         $sout .= $recc['Comment'];
      }
      $sout .= "\r\n";
      fputs($fout, $sout);
      if ($recc['Key_name']=='PRIMARY') {
      	$sinc = "\$aStructMB['$tab'][] = '".$recc['Column_name']."';\r\n";
      	fputs($finc, $sinc);
      }
   }
}
$sinc = "?>\r\n";
fputs($finc, $sinc);
fclose($fout);
mysql_close($conn);

?>